package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.GoodsDao;
import com.rk.kbk.dao.GoodsUnitDao;
import com.rk.kbk.dao.OrderGoodsDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Goods;
import com.rk.kbk.model.GoodsUnit;
import com.rk.kbk.model.OrderGoods;
import com.rk.kbk.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @GoodsController
 * @商品Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/goods")
public class GoodsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private GoodsDao goodsDao;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private GoodsUnitDao goodsUnitDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private UserDao userDao;
    /**
     * @添加/修改商品
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateGoods(HttpRequest request,@RequestBody(required = false) Goods goods){
        log.debug("添加/修改商品");



        return JsonResp.ok();
    }

    /**
     * @批量添加/修改商品
     * @param goodss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeGoods(@RequestBody List<Goods> goodss){
        log.debug("批量添加/修改商品");
        goodsDao.save(goodss);
        return JsonResp.ok();
    }

    /**
     * @获取商品详情-ByGoodsId
     * @param goodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/goodsDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findGoodsDetailsByGoodsId(Long goodsId) {
        log.debug("获取商品详情-ByGoodsId");
        Goods goods = goodsDao.findOne(goodsId);
        List<GoodsUnit> list = goodsUnitDao.findByGoodsAndStatus(goods,1);
        return JsonResp.ok(list);
    }

    /**
     * @分页查询商品(jpa方式)
     * @param goods 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageGoodsJpa(@RequestBody(required = false) Goods goods, Integer pageNum, Integer pageSize) {
        log.debug("分页查询商品(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == goods) {
            page = goodsDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  goods.getUserName();
            page = goodsDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<Goods> content = page.getContent();
//        for (Goods goods1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }
    /**
     * @ 商城首页
     * @param status
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findMallCommList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findMallCommList(int type,int status) {
        log.debug("商城首页   商品列表");
        List<Goods> goodsList = goodsDao.findByGoodsType(type);

//        List<Long> l = new ArrayList<>();
//        goodsList.forEach(n -> l.add(n.getId()));

    //    List<Long> longs = goodsList.stream().map(Goods::getId).collect(Collectors.toList());

        List<GoodsUnit> goodsUnits = goodsUnitDao.findByGoodsInAndStatus(goodsList, status);
        List<Map> commList=new ArrayList<>();
          for(int i=0,y=goodsUnits.size();i<y;i++){
              Map map =new HashMap<>();
              Goods goods=goodsUnits.get(i).getGoods();
              GoodsUnit goodsUnit=goodsUnits.get(i);
              if(i!=0){
                  Goods nestGoods=goodsUnits.get(i-1).getGoods();
                  if(goods.getId().equals(nestGoods.getId())){
                      continue;
                  }
              }
              map.put("title",goods.getTitle());
              map.put("goodsUrl",goods.getGoodsUrl());
              map.put("goodId",goods.getId());
              map.put("goodUnitId",goodsUnit.getId());
              map.put("unitPrice",goodsUnit.getUnitPrice());//单价
              map.put("marketPrice",goodsUnit.getMarketPrice());//市场价

              commList.add(map);
          }

        return JsonResp.ok(commList);
    }


    /**
     * @查看商品详情
     * @param goodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findCommDetal",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findCommDetal(Long goodsId,int status) {
        log.debug("查看商品详情");
        Goods goods=goodsDao.findOne(goodsId);
        List<GoodsUnit> goodsUnits = goodsUnitDao.findByGoodsAndStatus(goods,status);
        Map map =new HashMap();
        map.put("id",goods.getId());
        map.put("title",goods.getTitle());
        map.put("goodUrl",goods.getGoodsUrl());
        map.put("textcontent",goods.getGoodsDetail());
        map.put("unitPrice",goodsUnits.get(0).getUnitPrice());//单价价格
        map.put("marketPrice",goodsUnits.get(0).getMarketPrice());//市场价格
        List<Map> unitStandardList=new ArrayList<>();//存放规格
        for(int i=0,y=goodsUnits.size();i<y;i++){
            Map  unitStandarMap=new HashMap();
            Long id=goodsUnits.get(i).getId();
            String unitStandard=goodsUnits.get(i).getUnitStandard();//规格
            unitStandarMap.put("id",id);
            unitStandarMap.put("unitStandard",unitStandard);
            unitStandardList.add(unitStandarMap);
        }
        map.put("unitStandardList",unitStandardList);
        return JsonResp.ok(map);
    }




    /**
     * 我的装备列表（骑手）
     * @param rideId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/myGoodsList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp myGoodsList(Long rideId) {
        log.debug("我的装备列表（骑手）");
        User ride= userDao.findOne(rideId);
        List<OrderGoods> orderGoodsList=orderGoodsDao.findByUserAndOrderStatus(ride,4);//4代表已发货
        //去重处理
        List<Map> goodsList=new ArrayList<>();
        int i=0,y=orderGoodsList.size();
            for(;i<y;i++){
              OrderGoods orderGoods=orderGoodsList.get(i);
              if(goodsList.isEmpty()){
                  Map map=new HashMap();
                  map.put("title",orderGoods.getGoods().getTitle());
                  map.put("unitStandard",orderGoods.getGoodsUn().getUnitStandard());
                  map.put("goodsUrl",orderGoods.getGoods().getGoodsUrl());
                  map.put("num",1);
                  goodsList.add(map);
              }else {
                  int m=0,n=goodsList.size();
                  for(;m<n;m++){
                      Map map2=goodsList.get(m) ;
                      //如果装备名称和规格都一样 说明是同一件装备 数量+1
                      if(map2.get("title").equals(String.valueOf(orderGoods.getGoods().getTitle())) && map2.get("unitStandard").equals(String.valueOf(orderGoods.getGoodsUn().getUnitStandard()))){
                          map2.put("num",Integer.valueOf(String.valueOf(map2.get("num")))+1);
                          break;
                      }
                  }
                 if(m==n){
                     Map newGoods=new HashMap();
                     newGoods.put("title",orderGoods.getGoods().getTitle());
                     newGoods.put("unitStandard",orderGoods.getGoodsUn().getUnitStandard());
                     newGoods.put("goodsUrl",orderGoods.getGoods().getGoodsUrl());
                     newGoods.put("num",1);
                     goodsList.add(newGoods);
                 }
              }
            }

        return JsonResp.ok(goodsList);
    }
    /**
     * @删除商品-one(永久)
     * @param goodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteGoodsOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteGoodsOne(Long goodsId) {
        log.debug("删除商品-one(永久)");
        goodsDao.delete(goodsId);
        return JsonResp.ok();
    }




    /**
     * @批量删除商品(永久)
     * @param goodss
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeGoods",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeGoods(@RequestBody List<Goods> goodss) {
        log.debug("批量删除商品(永久)");
        goodsDao.delete(goodss);
        return JsonResp.ok();
    }


}
